package com.kylin.utils;

import com.kylin.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

@Component//就可以使用@Autowired注入。不交给Spring管理就用new它
public class HtmlParseUtil {

    public static void main(String[] args) throws IOException {
        new HtmlParseUtil().parseJD("Vue").forEach(System.out::println);
   /*     //获取请求。需要联网
        String url = "https://search.jd.com/Search?keyword=java";
        //解析网页。Jsoup返回的Document对象就是浏览器的Document对象
        Document document = Jsoup.parse(new URL(url), 30000);
        //所有在js中Document能进行的操作都能在次操作
        Element element = document.getElementById("J_goodsList");
        System.out.println(element.html());
        //获取所有的li元素
        Elements elements = element.getElementsByTag("li");
        //获取元素中的所有内容
        for (Element e1 : elements) {
            String img = e1.getElementsByTag("img").eq(0).attr("source-data-lazy-img");
            String price = e1.getElementsByClass("p-price").eq(0).text();
            String title = e1.getElementsByClass("p-name").eq(0).text();
            System.out.println("========================================");
            System.out.println(img);
            System.out.println(price);
            System.out.println(title);
        }*/
    }


    public ArrayList<Content> parseJD(String keywords) throws IOException {
        //获取请求。需要联网
        String url = "https://search.jd.com/Search?keyword=" + keywords;
        System.out.println(url);
        //解析网页。Jsoup返回的Document对象就是浏览器的Document对象
        Document document = Jsoup.parse(new URL(url), 30000);
        //所有在js中Document能进行的操作都能在次操作
        Element element = document.getElementById("J_goodsList");
        //System.out.println(element.html());
        //获取所有的li元素
        Elements elements = element.getElementsByTag("li");

        ArrayList<Content> goodsList = new ArrayList<>();
        //获取元素中的所有内容
        for (Element e1 : elements) {
            String img = e1.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = e1.getElementsByClass("p-price").eq(0).text();
            String title = e1.getElementsByClass("p-name").eq(0).text();

            Content content = new Content();
            content.setImg(img);
            content.setTitle(title);
            content.setPrice(price);
            goodsList.add(content);
        }
        return goodsList;
    }
}

